package com.watermeter.android.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oa.android.R;
import com.watermeter.android.entry.DownRoute;
import com.watermeter.android.entry.UpRoute;
import com.watermeter.android.utils.UConstants;
import com.watermeter.android.utils.Util;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;




/**
 * 录入抄表
 *
 * @author -zouqh
 */
public class LurucbActivity extends Activity implements OnClickListener {

    private static final String TAG = LurucbActivity.class.getName();
    private Context context;
    /** Camera相机硬件操作类 */
    private Camera camera = null;
    /** Camera2相机硬件操作类 */
    private CameraManager manager = null;
    private CameraDevice cameraDevice;
    private CameraCaptureSession captureSession = null;
    private CaptureRequest request = null;
    private SurfaceTexture surfaceTexture;
    private Surface surface;
    private String cameraId = null;
    private boolean isSupportFlashCamera2 = false;






    private ImageView close;
    private TextView title;
    private TextView save, userName, code, syds, dyyl, address, cbxh,syyl,tsMsg,ccjj,yslx;
    private EditText dyds, tbsl;
    private int postion;
    private DownRoute downRoute;
    private Button up, next,sdt,photo;
    private int allToal;
    private LinearLayout layout;
    public DbManager.DaoConfig daoConfig;
    private String changeTp;//修改前的退补数量
    private String changeDs;//修改前的当月读数

    public static boolean statusFlag = true;
    public static boolean isOpenFlash = true;
    //private CameraManager manager;

    private String imgPath;
    private String fileName;
    private String time;

    private  Parameters mParameters = null;

    private LurucbActivity instance;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        postion = Integer.parseInt(getIntent().getStringExtra("id"));
        Log.i("postion------------",postion+"");
        setContentView(R.layout.luru_cb_activity);
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        save = (TextView) findViewById(R.id.ritgh_text);

        userName = (TextView) findViewById(R.id.userName);
        code = (TextView) findViewById(R.id.code);
        syds = (TextView) findViewById(R.id.syds);
        dyyl = (TextView) findViewById(R.id.dyyl);
        address = (TextView) findViewById(R.id.address);
        cbxh = (TextView) findViewById(R.id.cbxh);
        tsMsg  = (TextView) findViewById(R.id.tsMsg);
        syyl = (TextView) findViewById(R.id.syyl);
        ccjj = (TextView) findViewById(R.id.ccjj);
        dyds = (EditText) findViewById(R.id.dyds);
        tbsl = (EditText) findViewById(R.id.tbsl);
        up = (Button) findViewById(R.id.up);
        next = (Button) findViewById(R.id.next);

        sdt = (Button) findViewById(R.id.sdt);
        photo = (Button) findViewById(R.id.photo);
        yslx =(TextView)findViewById(R.id.yslx);

        layout = (LinearLayout) findViewById(R.id.layout);
        if (UConstants.ShowTBSL != null && UConstants.ShowTBSL.equals("1")) {
            layout.setVisibility(View.VISIBLE);
        }
        next.setOnClickListener(this);
        up.setOnClickListener(this);
        save.setText("保存");
        title.setText("录入抄表");
        save.setVisibility(View.VISIBLE);
        close.setOnClickListener(this);
        save.setOnClickListener(this);
        if (null!= RouteItemActivity.activity){
            allToal = RouteItemActivity.activity.downRoutelist1.size();
        }
        if (null!= SeachActivity.activity){
            allToal = SeachActivity.activity.downRoutelist1.size();
        }

        setValue();
//        daoConfig = new DbManager.DaoConfig();

        sdt.setOnClickListener(this);

        photo.setOnClickListener(this);

        dyds.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.length() > 0) {
                    int aa = Integer.parseInt(dyds.getText().toString());
                    int bb = Integer.parseInt(downRoute.getSBQD());
                    int cc = Integer.parseInt(downRoute.getSYYL());
                    dyyl.setText("当月用量：" + (aa-bb));
                    if (null!=downRoute.getWARNV()&&downRoute.getWARNV().length()>0&&aa>0){
                        float cs = Float.parseFloat(downRoute.getWARNV());
                        if (cc>0){
                            System.out.println(bb);
                            System.out.println("(aa - bb)==="+(aa - bb));
                            float rt =Math.abs ( ( (float)(aa - bb - cc)/cc)*100);
                            System.out.println("rt---"+rt);

                            if (rt>cs){
                                ccjj.setText("振幅超过"+downRoute.getWARNV());
                            }else{
                                ccjj.setText("");
                            }
                        }else{
                            ccjj.setText("");
                        }
                        }

                } else {
                    dyyl.setText("当月用量：0" );
                    ccjj.setText("");
                }
            }
        });

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {

            if (camera != null){
                turnLightOffCamera(camera);
                camera.release();
                camera = null;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent;
        switch (v.getId()) {
            case R.id.close:

                if (camera != null){
                    turnLightOffCamera(camera);
                    camera.release();
                    camera = null;
                }

                finish();
                break;
            case R.id.ritgh_text:

                if (dyds.getText().toString().trim().length()>0){
//                    int d = Integer.parseInt(dyds.getText().toString().trim());
//                    if (d > 0) {
                        UpRoute(dyds.getText().toString().trim(), tbsl.getText().toString().trim());
//                    } else {
//                        Toast.makeText(this, "请填写本月读数!", Toast.LENGTH_SHORT).show();
//                    }
                }else{
                    Toast.makeText(this, "请填写本月读数!", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.next:
                if (postion < allToal-1) {
                    String string=dyds.getText().toString().trim();
                    String string1=tbsl.getText().toString().trim();
                    if (Util.NoNull(string)){
                        if (!changeDs.equals(string)||!changeTp.equals(string1)){
                            UpRoute(string, string1);
                        }

                    }
                    postion++;
                    setValue();
                } else {
                    Toast.makeText(this, "已经到最后一条了！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.up:

                if (postion > 0) {
                    String string=dyds.getText().toString().trim();
                    String string1=tbsl.getText().toString().trim();
                    if (Util.NoNull(string)){
                        if (!changeDs.equals(string)||!changeTp.equals(string1)){
                            UpRoute(string, string1);
                        }

                    }

                    postion--;
                    setValue();
                } else {
                    Toast.makeText(this, "没有上一条了！", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.sdt:
                if (isLOLLIPOP()) {

                    manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                    try {
                        String[] camerList = manager.getCameraIdList();
                        for (String str : camerList) {
                            Log.d("List", str);
                        }
                    } catch (CameraAccessException e) {
                        Log.e("error", e.getMessage());
                    }
                }
                else
                {
                    if (null==camera) {
                        camera = Camera.open();
                    }
                }

                if(statusFlag) {
                    Log.e("v--c>","k");
                    if (isLOLLIPOP()) {
                        Log.e("v--k>", "22");
                        try {
                            manager.setTorchMode("0", true);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }
                    else
                    {
                        Log.e("v--k>", "21");
                        // if(null==camera) {
                        //     camera = Camera.open();
                        //}
                        turnLightOnCamera(camera);
                    }

                    statusFlag = false;
                }
                else
                {
                    Log.e("v--c>","c");
                    if (isLOLLIPOP()) {
                        Log.e("v--c>", "22");
                        try {
                            manager.setTorchMode("0", false);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }
                    else {
                        Log.e("v--c>", "21");
                        if (camera != null){
                            turnLightOffCamera(camera);
                            camera.release();
                            camera = null;
                        }
                    }

                    statusFlag = true;
                }


                break;

            case R.id.photo:
                takePhoto();

                break;

            default:
                break;
        }
    }

    public boolean isSupportFlash() {
        if (isLOLLIPOP()) { // 判断当前Android系统版本是否 >= 21, 分别处理
            return isSupportFlashCamera2;
        } else {
            PackageManager pm = context.getPackageManager();
            FeatureInfo[] features = pm.getSystemAvailableFeatures();
            for (FeatureInfo f : features) {
                // 判断设备是否支持闪光灯
                if (PackageManager.FEATURE_CAMERA_FLASH.equals(f.name)) {
                    return true;
                }
            }
            // 判断是否支持闪光灯,方式二
            // Camera.Parameters parameters = camera.getParameters();
            // if (parameters == null) {
            // return false;
            // }
            // List<String> flashModes = parameters.getSupportedFlashModes();
            // if (flashModes == null) {
            // return false;
            // }
        }
        return false;
    }


    /**
     * 初始化相机
     */
    public void init() {
        this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        if (isLOLLIPOP()) {
            initCamera2();
        } else {
            camera = Camera.open();
        }
    }

    /**
     * 开启闪光灯
     */
    public void turnOn() {
        if (!isSupportFlash()) {
            showToast("设备不支持闪光灯！");
            return;
        }
        if (isOpenFlash) {
            return;
        }

        if (isLOLLIPOP()) {
            turnLightOnCamera2();
        } else {
            turnLightOnCamera(camera);
        }
    }


    /**
     * 关闭闪光灯
     */
    public void turnOff() {
        if (!isSupportFlash()) {
            showToast("设备不支持闪光灯！");
            return;
        }
        if (!isOpenFlash) {
            return;
        }
        if (isLOLLIPOP()) {
            turnLightOffCamera2();
        } else {
            turnLightOffCamera(camera);
        }
        isOpenFlash = false;
    }
    /**
     * 开启Camera2闪光灯
     */
    private void turnLightOnCamera2() {
        new Object() {
            private void _turnLightOnCamera2() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        showToast("应用未开启访问相机权限！");
                        return;
                    }
                    try {
                        manager.openCamera(cameraId, new CameraDevice.StateCallback() {

                            @Override
                            public void onOpened(CameraDevice camera) {
                                cameraDevice = camera;
                                createCaptureSession();
                            }

                            @Override
                            public void onError(CameraDevice camera, int error) {
                            }

                            @Override
                            public void onDisconnected(CameraDevice camera) {
                            }
                        }, null);
                    } catch (Exception e) {
                        Log.i("TEST",e.getMessage());
                        showToast("开启失败：" + e.getMessage());
                    }
                }
            }
        }._turnLightOnCamera2();
    }

    /**
     * 关闭Camera2闪光灯
     */
    private void turnLightOffCamera2() {
        new Object() {
            private void _turnLightOffCamera2() {
                if (cameraDevice != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    cameraDevice.close();
                }
            }
        }._turnLightOffCamera2();
    }

    /**
     * 判断设备是否支持闪光灯
     *
     * @return boolean
     */


    /**
     * 是否已经开启闪光灯
     *
     * @return
     */
    public boolean isTurnOnFlash() {
        return isOpenFlash;
    }



    /**
     * 通过设置Camera打开闪光灯
     *
     * @param mCamera
     */
    public void turnLightOnCamera(Camera mCamera) {
        Parameters parameters = mCamera.getParameters();
        List<String> flashModes = parameters.getSupportedFlashModes();
        String flashMode = parameters.getFlashMode();
        if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) {
            // 开启闪光灯
            if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
                parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
                mCamera.setParameters(parameters);
            }
        }
        isOpenFlash = true;
    }

    /**
     * 通过设置Camera关闭闪光灯
     *
     * @param mCamera
     */
    public void turnLightOffCamera(Camera mCamera) {
        Parameters parameters = mCamera.getParameters();
        List<String> flashModes = parameters.getSupportedFlashModes();
        String flashMode = parameters.getFlashMode();
        if (!Parameters.FLASH_MODE_OFF.equals(flashMode)) {
            // 关闭闪光灯
            if (flashModes.contains(Parameters.FLASH_MODE_OFF)) {
                parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
                mCamera.setParameters(parameters);
            }
        }
        isOpenFlash = false;
    }

    /**
     * 初始化Camera2
     */
    private void initCamera2() {
        new Object() {
            private void _initCamera2() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    try {
                        for (String _cameraId : manager.getCameraIdList()) {
                            CameraCharacteristics characteristics = manager.getCameraCharacteristics(_cameraId);
                            // 过滤掉前置摄像头
                            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                            if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                                continue;
                            }
                            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                            if (map == null) {
                                continue;
                            }
                            cameraId = _cameraId;
                            // 判断设备是否支持闪光灯
                            isSupportFlashCamera2 = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                        }
                    } catch (Exception e) {
                        //LoggerUtil.error(TAG, e.getMessage(), e);
                        showToast("初始化失败：" + e.getMessage());
                    }
                }
            }
        }._initCamera2();
    }

    private void createCaptureSession() {
        new Object() {
            private void _createCaptureSession() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    final CameraCaptureSession.StateCallback stateCallback = new CameraCaptureSession.StateCallback() {

                        public void onConfigured(CameraCaptureSession arg0) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                captureSession = arg0;
                                CaptureRequest.Builder builder;
                                try {
                                    builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                                    builder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
                                    builder.addTarget(surface);
                                    request = builder.build();
                                    captureSession.capture(request, null, null);
                                    isOpenFlash = true;
                                } catch (Exception e) {
                                    //LoggerUtil.error(TAG, e.getMessage(), e);
                                    showToast("开启失败：" + e.getMessage());
                                }
                            }
                        }

                        public void onConfigureFailed(CameraCaptureSession arg0) {
                        }
                    };

                    surfaceTexture = new SurfaceTexture(0, false);
                    surfaceTexture.setDefaultBufferSize(1280, 720);
                    surface = new Surface(surfaceTexture);
                    ArrayList localArrayList = new ArrayList(1);
                    localArrayList.add(surface);
                    try {
                        cameraDevice.createCaptureSession(localArrayList, stateCallback, null);
                    } catch (Exception e) {
                        //LoggerUtil.error(TAG, e.getMessage(), e);
                        showToast("开启失败：" + e.getMessage());
                    }
                }
            }
        }._createCaptureSession();
    }


    private void showToast(String content) {
        Toast.makeText(context, content, Toast.LENGTH_LONG).show();
    }


    private void takePhoto() {

        Intent openCameraIntent = new Intent(); // 调用照相机
        openCameraIntent.setAction("android.media.action.STILL_IMAGE_CAMERA");
        startActivity(openCameraIntent);


    }



    /**
     * 判断Android系统版本是否 >= LOLLIPOP(API21)
     *
     * @return boolean
     */
    private boolean isLOLLIPOP() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 设置值
     */
    private void setValue() {
        if (null!= RouteItemActivity.activity){
            downRoute = RouteItemActivity.activity.downRoutelist1.get(postion);
        }
        if (null!= SeachActivity.activity){
            downRoute = SeachActivity.activity.downRoutelist1.get(postion);
        }
        System.out.println("downRoute--"+downRoute);

        if (downRoute != null) {
            int a = downRoute.getSBZD();
            int b = Integer.parseInt(downRoute.getSBQD());
//            int c = Integer.parseInt(downRoute.getSYYL());
            userName.setText("用户姓名：" + downRoute.getUSERNAME());
            code.setText("用户编号：" + downRoute.getUSERID());
            syds.setText("上月读数：" + downRoute.getSBQD());

            dyyl.setText("当月用量：" + downRoute.getSBQD());
            cbxh.setText("抄表序号：" + downRoute.getCBXH());
            tsMsg.setText(""+downRoute.getSHINT());
            yslx.setText("用水类型："+downRoute.getPRIMEMO());
//            if(com.oa.android.utils.Util.NoNull(downRoute.getSYYL())){
                syyl.setText("上月用量："+downRoute.getSYYL());
//            }else{
//                syyl.setText("月均用量：0");
//            }

            address.setText("详细地址：" + downRoute.getXXDZ());
            changeDs=downRoute.getSBZD()+"";
            if (downRoute.getSBZD()>0){
                dyds.setText(downRoute.getSBZD() + "");
            }else{
                dyds.setText("");
            }
            changeTp=downRoute.getTBSL()+"";
            Log.i("changeDs------------",changeDs);
            Log.i("changeTp------------",changeTp);
            tbsl.setText(changeTp);
            if (a > 0) {
                int d = a - b;
                dyyl.setText("当月用量：" + d);


            } else {
                dyyl.setText("当月用量：0");
            }
        }
    }


    /**
     * 更新
     */
    private void UpRoute(String str1, String str2) {

        DbManager manager = x.getDb(daoConfig);
        try {
            //创建对象，用来生成表
//            downRoute
            int a = Integer.parseInt(str1);//本月读数
            if (!Util.NoNull(str2)){
                str2="0";
            }
            int b = Integer.parseInt(str2);//退补水量

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date currentTime = new Date();
            String dateString = dateFormat.format(currentTime);
            if (null!= RouteItemActivity.activity){
                RouteItemActivity.activity.downRoutelist1.get(postion).setChange(1);
                RouteItemActivity.activity.downRoutelist1.get(postion).setSBZD(a);
                RouteItemActivity.activity.downRoutelist1.get(postion).setTBSL(b);
                RouteItemActivity.activity.downRoutelist1.get(postion).setCBRQ(dateString);
            }
            if (null!= SeachActivity.activity) {
                SeachActivity.activity.downRoutelist1.get(postion).setChange(1);
                SeachActivity.activity.downRoutelist1.get(postion).setSBZD(a);
                SeachActivity.activity.downRoutelist1.get(postion).setTBSL(b);
                SeachActivity.activity.downRoutelist1.get(postion).setCBRQ(dateString);
            }
            downRoute.setSBZD(a);
            downRoute.setTBSL(b);
            downRoute.setChange(1);
            downRoute.setCBRQ(dateString);
            if (null!= RouteItemActivity.activity){
                downRoute.setMOTH(RouteItemActivity.activity.moth);
            }
            if (null!= SeachActivity.activity){
                downRoute.setMOTH(downRoute.getSMON());
            }

            System.out.println("downRoute----"+downRoute);
            manager.saveOrUpdate(downRoute);
//            manager.save(info);
            saveUpdate();

        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存路线数据
     */
    private void saveUpdate() {

        DbManager manager = x.getDb(daoConfig);
        try {
            //创建对象，用来生成表
            UpRoute upRoute = new UpRoute();
            upRoute.setTBSL(downRoute.getTBSL());
            upRoute.setSBZD(downRoute.getSBZD());
            upRoute.setCBRQ(downRoute.getCBRQ());
            upRoute.setChange(downRoute.getChange());
            upRoute.setId(downRoute.getId());
            upRoute.setUSERID(downRoute.getUSERID());
            upRoute.setUpdate(downRoute.getUpdate());
            upRoute.setSBQD(downRoute.getSBQD());
            if (null!=RouteItemActivity.activity){
                RouteItemActivity.activity.flag = 1;
                upRoute.setMOTH(RouteItemActivity.activity.moth);
            }else {
                upRoute.setMOTH(downRoute.getSMON());
            }

            System.out.println("upRoute----"+upRoute);

//          manager.saveOrUpdate(upRoute);

            List<UpRoute> u = manager.selector(UpRoute.class).where("id","=",downRoute.getId()).findAll();
            if(u!=null&&u.size()>0){
                System.out.println("up----" + u.size());

                for (int i=0;i<u.size();i++){
                    upRoute.setUpid(u.get(i).getUpid());
                    manager.saveOrUpdate(upRoute);
                }
            }else{
                manager.saveOrUpdate(upRoute);
            }


            int aa = Integer.parseInt(downRoute.getSBQD());
            int bb = downRoute.getSBZD();
            dyyl.setText("当月用量：" + (bb-aa));
            String avgSL = downRoute.getSYYL();
            boolean showOther=false;
//            if (com.oa.android.utils.Util.NoNull(avgSL)){
//                double davg = Double.parseDouble(avgSL);
//                if (davg>0) { //月均用量振幅判断
//
//                    Log.v("avg",aa+":"+bb);
//                    if(  Math.abs(((double)(bb- aa-davg)) /davg) >0.3  ) {
//                        showOther=true;
//                        Toast toast = Toast.makeText(this, "已保存.但当月用量超过月均用量30%" , 10);
//                        toast.setGravity(Gravity.CENTER, 0, 0);
//                        toast.show();
//                    }
//
//                }
//
//            }
            if (showOther==false){
                Toast.makeText(this, "保存成功！", 10).show();
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

}
